package com.imu.purse.modules.trade.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.imu.common.exception.ErrorDesc;
import com.imu.common.exception.RRException;
import com.imu.core.base.BaseService;
import com.imu.core.redisplus.annotation.RedisLock;
import com.imu.enums.ClubType;
import com.imu.enums.OrderTypeStatus;
import com.imu.enums.PStatus;
import com.imu.enums.TradeType;
import com.imu.purse.modules.trade.dao.GradeInfoMapper;
import com.imu.purse.modules.trade.entity.FundEntity;
import com.imu.purse.modules.trade.entity.GradeInfoEntity;
import com.imu.purse.modules.trade.entity.TradeInfoEntity;
import com.imu.purse.modules.trade.service.FundService;
import com.imu.purse.modules.trade.service.GradeInfoService;
import com.imu.purse.modules.trade.service.TradeInfoService;
import com.imu.utils.IDUtils;
import com.xiaoleilu.hutool.util.ArrayUtil;
import com.xiaoleilu.hutool.util.NumberUtil;
import com.xiaoleilu.hutool.util.StrUtil;

/**
 * 私募明细
 * @author sunhongwei
 * @email sunhongwei@jshijian.com
 * @date 2018-03-22 10:33:20
 * Copyright (c) 2017 武汉极时间科技有限公司 版权所有 
 * Jshijian aloha CO.,LTD. All Rights Reserved. 
 */
@Service
public class GradeInfoServiceImpl extends BaseService<GradeInfoEntity> implements GradeInfoService 
{
	@Override
    @Transactional
    public int save(final GradeInfoEntity entity)
	{
		entity.setTimeCreate(new Date());
		entity.setTimeUpdate(new Date());
    	return super.insert(entity);
	}
	
	@Override
	@Transactional
    public int update(final GradeInfoEntity tradeInfo) 
    {
    	return mapper.updateByPrimaryKeySelective(tradeInfo);
    }
    
    @Override
	@Transactional
    public int saveUpdate(final GradeInfoEntity tradeInfo)
    {
    	int len = 0;
    	
    	if(1 > (len = this.update(tradeInfo)))
    	{
        	len = this.insert(tradeInfo);
    	}
    	
    	return len;
    }
    
 	@Override
	@Transactional
    public boolean delete(final String ...ids)
    {
    	if(ArrayUtil.isEmpty(ids)) return false;
    	
    	for (String id : ids) 
    	{
    		if(StrUtil.isBlank(id)) continue;
    		
    		if(NumberUtil.isNumber(id))
    		{
        		mapper.deleteByPrimaryKey(Long.valueOf(id));
    		}
		}
    	
    	return true;
    }
 	
 	@Override
	@Transactional
	@RedisLock(keys = "#key", expire = 30000, tryTimeout = 1000)
 	public void grade(final String key, final String uid)
 	{
 		//验证用户余额信息 是否支持本次私募
        FundEntity fund = fundService.findByUserId(Long.valueOf(uid));
        if(null == fund || null == fund.getHbc()){
        	throw new RRException(ErrorDesc.GET_USER_ERR.getMsg(), ErrorDesc.GET_USER_ERR.getCode());
        }
        else if(0 >= fund.getHbc().longValue()) {
        	throw new RRException(ErrorDesc.CLUB_NORMAL.getMsg(), ErrorDesc.CLUB_NORMAL.getCode());
        }
        BigDecimal money = new BigDecimal(ClubType.SLIVER.getType());
        if(fund.getHbc().longValue() >= ClubType.BLACK.getType())
        {
        	money = new BigDecimal(ClubType.BLACK.getType() - ClubType.WHITE.getType());
        }
        else if(fund.getHbc().longValue() >= ClubType.WHITE.getType())
        {
        	money = new BigDecimal(ClubType.WHITE.getType() - ClubType.BRIL.getType());
        }
        else if(fund.getHbc().longValue() >= ClubType.BRIL.getType())
        {
        	money = new BigDecimal(ClubType.BRIL.getType() - ClubType.GOLD.getType());
        }
        else if(fund.getHbc().longValue() >= ClubType.GOLD.getType())
        {
        	money = new BigDecimal(ClubType.GOLD.getType() - ClubType.SLIVER.getType());
        }
        
        //保存降级记录信息
        GradeInfoEntity dto = new GradeInfoEntity();
        dto.setUserId(fund.getUserId());
        dto.setHbc(money);
        dto.setImu(money);
        dto.setCurrGrade(fund.getHbc());
        dto.setNowGrade(fund.getHbc().subtract(money));
        dto.setType(0); //0,HBC
       
        try 
        {
			this.save(dto);
		} 
        catch (DuplicateKeyException e) 
        {
        	throw new RRException(ErrorDesc.CLUB_GRADE_NEXT.getMsg(), ErrorDesc.CLUB_GRADE_NEXT.getCode());
		}
        
        //增加IMU 保存流水记录
        BigDecimal imu = (null == fund.getMoney()) ? new BigDecimal("0") : fund.getMoney();
        TradeInfoEntity tradeEntity = new TradeInfoEntity();
        tradeEntity.setId(null);
        tradeEntity.setOrderNo(IDUtils.getOrder());
        tradeEntity.setPayUserId(fund.getUserId());
        tradeEntity.setRecUserId(fund.getUserId());
        tradeEntity.setMoney(money);
        tradeEntity.setSmoney(imu);
        tradeEntity.setEmoney(imu.add(money));
        tradeEntity.setOrderType(OrderTypeStatus.IN.getType());
        tradeEntity.setOrderState(PStatus.Finished.getType());
        tradeEntity.setYtfType(TradeType.IMU.getType());
        tradeInfoService.save(tradeEntity);
        
        //添加IMU
        FundEntity fundEntity = new FundEntity();
        fundEntity.setUserId(fund.getUserId());
        fundEntity.setMoney(money);
        fundEntity.setYtfType(TradeType.IMU.getType());
        fundService.updateMoneyByUIdAndYtype(fundEntity);
        
        //扣减HBB 保存流水记录
        tradeEntity.setId(null);
        if(null != dto.getId())
        {
            tradeEntity.setOrderNo(String.valueOf(dto.getId()));
        }
        tradeEntity.setMoney(money);
        tradeEntity.setSmoney(fund.getHbc());
        tradeEntity.setEmoney(fund.getHbc().subtract(money));
        tradeEntity.setOrderType(OrderTypeStatus.OUT.getType());
        tradeEntity.setYtfType(TradeType.HBC.getType());
        tradeInfoService.save(tradeEntity);

        //降级
        fundEntity.setMoney(money.multiply(new BigDecimal(-1)));
        fundEntity.setYtfType(TradeType.HBC.getType());
        fundService.updateMoneyByUIdAndYtype(fundEntity);
 	}
    
    @Override
    public GradeInfoEntity findById(final Long id)
    {
    	if(null == id) return null;
    	return mapper.selectByPrimaryKey(id);
    }
    
    @Override
    public List<GradeInfoEntity> queryList(final GradeInfoEntity tradeInfo)
    {
    	if (tradeInfo.getPage() != null && tradeInfo.getLimit() != null)
    	{
            PageHelper.startPage(tradeInfo.getPage(), tradeInfo.getLimit());
        }
    	
    	return mapper.findByPage(tradeInfo);
    }
    
	@Autowired
	private GradeInfoMapper mapper;

	@Autowired
	private TradeInfoService tradeInfoService;
	
	@Autowired
	private FundService fundService;
}
